#include <stdio.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/evp.h>

void base64_encode_file(const char *input_filename, const char *output_filename) {
    FILE *input_file = fopen(input_filename, "rb");
    if (!input_file) { perror("Error opening input file"); return; }
    FILE *output_file = fopen(output_filename, "w");
    if (!output_file) { perror("Error opening output file"); fclose(input_file); return; }

    BIO *source = BIO_new_fp(input_file, BIO_NOCLOSE);
    BIO *base64 = BIO_new(BIO_f_base64());
    BIO_set_flags(base64, BIO_FLAGS_BASE64_NO_NL);
    BIO *sink = BIO_new_fp(output_file, BIO_NOCLOSE);
    BIO_push(base64, sink);

    char inbuf[512];
    int inlen;
    while ((inlen = BIO_read(source, inbuf, sizeof(inbuf))) > 0) {
        BIO_write(base64, inbuf, inlen);
    }
    BIO_flush(base64);
    BIO_free_all(base64);
    fclose(input_file);
    fclose(output_file);
}

void base64_decode_file(const char *input_filename, const char *output_filename) {
    FILE *input_file = fopen(input_filename, "rb");
    if (!input_file) { perror("Error opening input file"); return; }
    FILE *output_file = fopen(output_filename, "wb");
    if (!output_file) { perror("Error opening output file"); fclose(input_file); return; }

    BIO *source = BIO_new_fp(input_file, BIO_NOCLOSE);
    BIO *base64 = BIO_new(BIO_f_base64());
    BIO_set_flags(base64, BIO_FLAGS_BASE64_NO_NL);
    BIO *sink = BIO_new_fp(output_file, BIO_NOCLOSE);
    BIO_push(base64, source);

    char inbuf[512];
    int inlen;
    while ((inlen = BIO_read(base64, inbuf, sizeof(inbuf))) > 0) {
        BIO_write(sink, inbuf, inlen);
    }
    BIO_flush(sink);
    BIO_free_all(base64);
    fclose(input_file);
    fclose(output_file);
}

int main() {
    const char *input_filename = "input.test";
    const char *encoded_filename = "encoded.test";
    const char *decoded_filename = "decoded.test";
    base64_encode_file(input_filename, encoded_filename);
    base64_decode_file(encoded_filename, decoded_filename);
    return 0;
}
